﻿using Aop.Api;
using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Max.PH5_2011A.DTO;
using Max.PH5_2011A.DTO.Order;
using Max.PH5_2011A.IService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH5_2011A.API.Controllers.Order
{
    /// <summary>
    /// 订单控制器
    /// </summary>
    [Route("order")]
    [ApiController]
    public class OrderController : ControllerBase
    {

        IOrderMasterService _service;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="service"></param>
        public OrderController(IOrderMasterService service)
        {
            _service = service;
        }

        /// <summary>
        /// 创建订单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CreateOrder(OrderInputDto dto)
        {
            ResponseResultDto<dynamic> result = new();

            if (dto.MemberId == Guid.Empty)
            {
                result.Code = ResponseStateCode.PARAMNOVALID;
                result.Message = "参数无效";
                return Ok(result);
            }

            var data = _service.CreateOrder(dto);


            if (data.Item1)
            {
                result.Data = data.Item2;
            }
            else
            {
                result.Message = data.Item2;
            }

            return Ok(result);
        }




        /// <summary>
        /// 支付宝支付
        /// </summary>
        /// <returns></returns>
        [HttpGet("alipay")]
        public IActionResult Alipay(string orderNo)
        {
            ResponseResultDto<dynamic> dto = new();

            var m = _service.Query().Where(x => x.OrderNo.Equals(orderNo)).FirstOrDefault();
            if (m == null)
            {
                dto.Code = ResponseStateCode.PARAMNOVALID;
                dto.Message = "非法请求";
                return Ok(dto);
            }

            try
            {
                //应用私钥
                string privateKey = "MIIEowIBAAKCAQEAq0YSg/ePFopn5WxX6T3KdTQBlmMth1FB+uYDxu9N3yefp+iVQq9k9q+wPZ7YO4buepT0tUYugBzhcuXki9yNrPwzVq5IQHbf/eDN3O0r15IWrSVpWF0IRSQ1czHYDWWso6YL+VGDe2Jt8gFLiGPW4roA+/8QFhqOZfA0okyJ9pDp5jg/zx0vBv06XuZK1LQWuLCHMyIIoL8DCRzc1smvg6zPc3tlvccov+SxMX79dFDWnZ+ue+Y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HU1n/v1NMxfovMw2wAyjiW+49MPf9fmVkFrkyazP9kWZRgJcXP4EqsEGU3x0DW8WK6CQKBgATRVUX3rYzlwwkMDCkMUiUc0TgOH3h85kD+gP0chr4OzJ0m5wUIRyT0s+jZaxcNj+Rva7SutG6o+Dx8NKUholXGg9ZxtzAfcbKs1gw15+nsE+xvOHRiHiaKEV6kSbeDp/EYmkuLCNMJ8VgRgWylNoql5zx9A5qdpnESbr2gNAfJ";

                //支付公钥
                string alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgjE9JySZVyw8jXHoexIhJQ2wUMtix2xu28MAOhhuK2qtOsoY4DUzfU5XorHwiCNA5VM2qI1Isc484gogoVPijduEEd4F543xxPPco8xm1J98kMf6Ocz+8rhtytQp7FjqJROPmwWFemKS/ZyuGXXgOy3K/lUMQmLQxyRkSypJLf25JA5kC1/qUb5PppSoK8oI7DgFSwMMLhtZfVv6FAiv4SIQSx7mJzrraxKoUgzH7lx/Oslb9Ncuawnk1QxlqH5kaRXTl5KtNRNNJqi5F/GtfYhUZTA3ennW3Zd18lGeU6d4317MHl9ENSkoO2YhRb2LCyVRwHiXoHuokPMUbOlpBQIDAQAB";
                AlipayConfig alipayConfig = new AlipayConfig
                {
                    ServerUrl = "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
                    AppId = "2021000122669848",
                    PrivateKey = privateKey,
                    Format = "json",
                    AlipayPublicKey = alipayPublicKey,
                    Charset = "UTF-8",
                    SignType = "RSA2"
                };
                IAopClient alipayClient = new DefaultAopClient(alipayConfig);
                AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
                AlipayTradePagePayModel model = new AlipayTradePagePayModel();
                //商户订单号
                model.OutTradeNo = orderNo;
                //订单金额
                model.TotalAmount = m.Total.ToString();
                //主题
                model.Subject = "沙箱测试";
                //产品代码
                model.ProductCode = "FAST_INSTANT_TRADE_PAY";
                //支付成功返回地址
                request.SetReturnUrl($"http://localhost:8090/#/success");
                request.SetBizModel(model);
                AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
                if (!response.IsError)
                {
                    //Console.WriteLine("调用成功");
                    dto.Data = response.Body;
                    dto.Message = "调用成功";
                }
                else
                {
                    //Console.WriteLine("调用失败");
                    dto.Code = ResponseStateCode.FAILED;
                    dto.Message = "调用失败";
                }
            }
            catch (Exception ex)
            {
                dto.Code = ResponseStateCode.FAILED;
                dto.Message = ex.Message;
            }

            return Ok(dto);
        }


        /// <summary>
        /// 订单查询
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Query(string? type="0",int state)
        {
            type = type ?? "0";

            if (type.Equals("0"))
            {
                //
            }else if(type.Equals("1"))
            {
                //
            }

            //所有的订单数据
            var list = _service.Query();

            //查今天的订单数据
            var data = list.Where(x => x.OrderTime.Date == System.DateTime.Now.Date).Select(x => new { OrderNo = x.OrderNo, OrderTime = x.OrderTime });

            //查昨天的订单数据
            data = list.Where(x => x.OrderTime.Date == System.DateTime.Now.AddDays(-1).Date).Select(x => new { OrderNo = x.OrderNo, OrderTime = x.OrderTime });
            
            //查当月的数据
            data = list.Where(x => x.OrderTime.Month == System.DateTime.Now.Month && x.OrderTime.Year == System.DateTime.Now.Year).Select(x => new { OrderNo = x.OrderNo, OrderTime = x.OrderTime });

            //查最近三个月的数据
            var s = System.DateTime.Now.AddMonths(-2).Date;  //4/7份
            var e = System.DateTime.Now.Date;  //6月份
            data = list.Where(x => x.OrderTime.Date >= s && x.OrderTime.Date <= e).Select(x => new { OrderNo = x.OrderNo, OrderTime = x.OrderTime });

            //本周的数据
            var a = (int)System.DateTime.Now.DayOfWeek;
            a = a == 0 ? 7 : a;
            var sw = System.DateTime.Now.AddDays(1 - a).Date;
            var ew = System.DateTime.Now.Date;
            data = list.Where(x => x.OrderTime.Date >= sw && x.OrderTime.Date <= ew).Select(x => new { OrderNo = x.OrderNo, OrderTime = x.OrderTime });

            //本季度的数据
            var x = System.DateTime.Now.Month;
            var ss = Convert.ToDateTime(System.DateTime.Now.AddMonths(-((x - 1) % 3)).ToString("yyyy/MM/01"));
            var es = System.DateTime.Now.Date;
            data = list.Where(x => x.OrderTime.Date>= ss && x.OrderTime.Date <= es).Select(x => new { OrderNo = x.OrderNo, OrderTime = x.OrderTime });
            //Console.WriteLine("本季度开始时间{0},结束时间{1}",ss,es);

            

            return Ok(data);
        }

    }
}
